package de.baumann.browser.activitys.oc

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import de.baumann.browser.R
import de.baumann.browser.activitys.hash.HashValueActivity
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.base.BasePresenter
import de.baumann.browser.iview.IBaseView
import de.baumann.browser.utils.web3j.Erc20Util
import de.baumann.browser.utils.web3j.TokenUtil
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.PayPwdDialog
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_exchange_power.*
import kotlinx.android.synthetic.main.activity_oc_b_detail.*
import kotlinx.android.synthetic.main.activity_oc_b_transfer.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import java.math.BigDecimal


class ExchangePowerActivity : BaseOdinActivity<IBaseView, BasePresenter<IBaseView>>() {

    companion object {
        fun startExchangePowerActivity(context: Context, balance: String, a: String, cn: String, url: String, ca: String) {
            context.startActivity(Intent(context, ExchangePowerActivity::class.java).apply {
                putExtra("a", a)
                putExtra("cn", cn)
                putExtra("url", url)
                putExtra("ca", ca)
                putExtra("balance", balance)
            })
        }
    }

    var gunFrig = 0
    var gunFrigs = 0.0

    override fun getTitleText(): String {
        return "兑换算力"
    }

    override fun getLayout(): Int {
        return R.layout.activity_exchange_power
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_power, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        HashValueActivity.startHashValueActivity(mContext)
        return super.onOptionsItemSelected(item)
    }

    private var pwdDialog: PayPwdDialog? = null
    var lastGunBalance = ""

    @SuppressLint("SetTextI18n")
    override fun initView() {

        when {
            getCn() == "gung" -> {
                gunFrig = 1000
                gunFrigs = 1000.0
            }
            getCn() == "frig" -> {
                gunFrig = 2000
                gunFrigs = 2000.0
            }
            else -> {
            }
        }
        lastGunBalance = getGun()
        val getCung1 = getGun().toDouble()
        val bg1: BigDecimal = BigDecimal(getCung1)
        val getCung = bg1.setScale(3, BigDecimal.ROUND_DOWN).toDouble()
        gunShow.text = "可用 $getCung ${getCn()}"
        initToolbar(commToolBar, commTitle)
        val lastPowers = (getCung * gunFrig).toInt()
        lastPower.text = "$lastPowers 算力"
        power.text = "$lastPowers"
        exchangePower.text = "$lastPowers 算力"


        lastGun.text = "$getCung ${getCn()} "
        sekPower.max = lastPowers
        sekPower.progress = lastPowers

        sekPower.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                power.text = "$progress"
                exchangePower.text = "$progress 算力"
                val s = progress / gunFrigs
                val bg = BigDecimal(s)
                val lastGunBalancex = bg.setScale(3, BigDecimal.ROUND_UP).toDouble()
                lastGunBalance = (lastGunBalancex).toString()
                lastGun.text = "$lastGunBalancex ${getCn()}"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
            }
        })

        btnSubmit.setOnClickListener {
            Log.d("Lwq", "=initView: " + lastGunBalance + "initView:= " + getCA())
            if (lastGunBalance.toDouble() <= 0) {
                showShortToast("余额不足")
                return@setOnClickListener
            }

            pwdDialog = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
                override fun callback(pwd: String) {
                    transfer(pwd)
                }
            })
            pwdDialog!!.show()
        }
    }

    fun transfer(pwd: String) {
        Observable.create(ObservableOnSubscribe<String> { emitter ->
            try {
                val wallet = WalletDaoUtils.queryWalletByAddress(getA())
                if (wallet == null) {
                    emitter.onError(Throwable("钱包信息加载失败"))
                    return@ObservableOnSubscribe
                }

                val pk = TokenUtil.getPrivateKey(pwd, wallet)
                val hashs = Erc20Util.transferERC20Token(getUrl(), getA(), getToA(), lastGunBalance, pk, getCA())
                if (hashs != null) {
                    emitter.onNext(hashs)
                }
            } catch (e: Exception) {
                if ("Invalid password provided" == e.message) {
                    emitter.onError(Throwable("密码错误"))
                } else {
                    emitter.onError(e)
                }
                e.printStackTrace()
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<String> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: String) {
                        pwdDialog?.dismiss()
                        showShortToast("交易已发送")
                        getBalance()
                    }

                    override fun onError(e: Throwable) {
                        showShortToast(e.message)
//                        if (e.message != null) {
//                            view!!.onError(e.message);
//                        }
                    }
                })
    }

    private fun getBalance() {
        Observable.create(ObservableOnSubscribe<BigDecimal> { emitter ->
            val balance = TokenUtil.getBalance2(intent.getStringExtra("url"),
                    intent.getStringExtra("a"),
                    intent.getStringExtra("ca"))
            if (balance != null) {
                emitter.onNext(balance)
            } else {
                emitter.onError(Throwable("余额获取失败"))
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<BigDecimal> {
                    override fun onComplete() {

                    }

                    override fun onSubscribe(d: Disposable) {
                    }

                    override fun onNext(t: BigDecimal) {
                    }

                    override fun onError(e: Throwable) {
                        view!!.onError(e.message)
                    }
                })
    }

    private fun getToA(): String {
//        var toa = "odx40e2f93271e359A0B9Aca7c76B8e6f91703a2C1C"
        var toa = "0x00000000000000000000000000000000000000000"

//        if (toa.startsWith("odx")) {
//            toa = "0x${toa.substring(3)}"
//        }
        return toa
    }

    override fun initData() {

    }


    private fun getCn(): String {
        return intent.getStringExtra("cn")
    }

    private fun getGun(): String {
        return intent.getStringExtra("balance")
    }

    private fun getA(): String {
        return intent.getStringExtra("a")
    }


    private fun getCA(): String {
        return intent.getStringExtra("ca")
    }

    private fun getUrl(): String {
        return intent.getStringExtra("url")
    }


    override fun createPresenter(): BasePresenter<IBaseView>? {
        return null
    }

    override fun createView(): IBaseView? {
        return null
    }
}